/*
 * error_handling.c
 *
 *  Created on: Dec 12, 2010
 *      Author: cpy.prefers.you@gmail.com
 */

#include <stdio.h>
#include <stdarg.h>
#include <setjmp.h>
#include "clogo.h"
#include "symbol_table.h"
#include "error_handling.h"
#include "lexer.h"

static const char ErrorMessage[NUMBER_OF_ERRORS][MESSAGE_LEN] =
{
    [ERROR_TYPE_MISMATCH]    = "%s doesn't like %s as input",
    [ERROR_HAS_NO_VALUE]     = "%s has no value",
    [ERROR_NOT_ENOUGH_INPUT] = "not enough inputs to %s",
    [ERROR_DO_NOT_OUTPUT]    = "%s didn't output to %s",
    [ERROR_DONT_KNOW_HOW]    = "I don't know how to %s",
    [ERROR_WHAT_TO_DO]       = "You don't say what to do with %s",
    [ERROR_DEFINED]          = "%s is already defined",
    [ERROR_UNEXPECTED]       = "unexpected %s"
};

jmp_buf JumpBuffer;

int MatchType(Symbol_T *Symbol, int NumberOfType, ...)
{
    if (Symbol)
    {
        va_list arg_ptr;
        va_start(arg_ptr, NumberOfType);
        for (; NumberOfType; NumberOfType--)
            if (Symbol->Type == va_arg(arg_ptr, int))
                return 1;
        va_end(arg_ptr);
    }
    return 0;
}

void Error(int ErrorCode, ...)
{
    va_list arg_ptr;
    va_start(arg_ptr, ErrorCode);
    vfprintf(OutputStream, ErrorMessage[ErrorCode], arg_ptr);
    fprintf(OutputStream, "\n");
    va_end(arg_ptr);
    RemoveAllLocalVariable();
    longjmp(JumpBuffer, 1);
    return;
}
